package rabbitmq

import (
	"errors"
	"github.com/streadway/amqp"
)

type MSG struct {
	Body    []byte
	Tag     uint64
	channel *Channel
}

//conn.channel.Ack(d.DeliveryTag,false)

//处理消息(顺序处理,如果需要多线程可以在回调函数中做手脚)
func (rq *Channel) Pop(callback func(MSG) error) (err error) {

	var msgs <-chan amqp.Delivery
	if msgs, err = rq.channel.Consume(rq.poperconf.QName, rq.poperconf.Consumer,
		rq.poperconf.AutoACK, rq.poperconf.Exclusive, rq.poperconf.NoLocal, true, nil); err != nil {
		return errors.New("rabbitmq pop message error")
	}

	for d := range msgs {
		var msg MSG = MSG{
			Body:    d.Body,
			Tag:     d.DeliveryTag,
			channel: rq,
		}
		//multiple为true的时候：此次交付和之前没有确认的交付都会在通过同一个通道交付，这在批量处理的时候很有用
		//为false的时候只交付本次。只有该方法执行了，RabbitMQ收到该确认才会将消息删除
		//d.Ack(false)
		//rq.ACK(d.DeliveryTag,false)
		go callback(msg)
	}
	return nil
}

/*
func (rq *Channel) PopQueue(push *Channel,callback func(MSG) error) (err error) {


	var msgs <-chan amqp.Delivery
	if msgs, err = rq.channel.Consume(rq.poperconf.QName, rq.poperconf.Consumer,
		rq.poperconf.AutoACK, rq.poperconf.Exclusive, rq.poperconf.NoLocal, true, nil); err != nil {
		return errors.New("rabbitmq pop message error")
	}

	if err = rq.channel.QueueBind(push.queueconf.Name,push.pusherconf.Key,push.pusherconf.Exchange,false,nil);err != nil {
		return errors.New("rabbitmq pop message error")
	}

	for d := range msgs {
		var msg MSG = MSG {
			Body : d.Body,
			Tag : d.DeliveryTag,
			channel:rq,
		}
		//multiple为true的时候：此次交付和之前没有确认的交付都会在通过同一个通道交付，这在批量处理的时候很有用
		//为false的时候只交付本次。只有该方法执行了，RabbitMQ收到该确认才会将消息删除
		//d.Ack(false)

		go callback(msg)

	}

	return nil
}
*/
